﻿using System;
using Hangfire;
using Hangfire.Redis;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Sunny.Hangfire
{
    public class HangfireHelper
    {
        public static IServiceCollection AddHangfire(IServiceCollection services,IConfiguration configuration)
        {
            services.AddHangfire(config=>
            {
                config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                    .UseSimpleAssemblyNameTypeSerializer()
                    .UseRecommendedSerializerSettings()
                    .UseRedisStorage(configuration.GetConnectionString("Redis"),new RedisStorageOptions()
                    {
                        Prefix = "hangfire:",
                        Db = 0
                    });
            });
            
            services.AddHangfireServer();
            services.AddHostedService<HangfireBackgroundService>();
            
            return services;
        }
        
        public static  IApplicationBuilder UseHangfire( IApplicationBuilder app)
        {
            var jobOptions = new BackgroundJobServerOptions
            {
                Queues = new[] { "critical", "test", "default" },
                WorkerCount = Environment.ProcessorCount * 2,
                ServerCheckInterval = TimeSpan.FromMinutes(1),
                HeartbeatInterval = TimeSpan.FromMinutes(1),
                SchedulePollingInterval = TimeSpan.FromSeconds(5), //计划轮询间隔  支持任务到秒
            };

            app.UseHangfireDashboard("/jobs",new DashboardOptions()
            {
                Authorization = new []{ new HangfireAuthorizationFilter() }
            });
            app.UseHangfireServer(jobOptions);
            
            return app;
        }
        
    }
}